package thread.base;

/**
 * Created by mHandler on 2018/5/27 0027.
 * Description:通过异常停止线程
 */
public class Thread_interrupt_exception extends Thread {

    @Override
    public void run() {
        super.run();
        try {
            for (int i = 0; i < 100000 ; ++i){
                if (this.isInterrupted()){
                    System.out.println("检测到停止状态，停止线程");
                    throw new InterruptedException();
                }
                System.out.println("i = "+i);
            }
        } catch (InterruptedException e) {
            System.out.println("异常退出，停止线程");
            e.printStackTrace();
        }
        System.out.println("通过异常停止了线程");
    }

    public static void main(String[] args) {
        try {
            Thread_interrupt_exception thr = new Thread_interrupt_exception();
            thr.start();
            Thread.sleep(200);
            thr.interrupt();
        } catch (InterruptedException e) {
            System.out.println("main catch");
            e.printStackTrace();
        }
    }
}
